package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.City;
import com.ruoyi.common.core.domain.entity.City;
import com.ruoyi.system.mapper.SysProvincesMapper;
import com.ruoyi.system.service.ISysProvincesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class SysProvincesServiceImpl implements ISysProvincesService {

    @Autowired
    SysProvincesMapper provincesMapper;

    @Override
    public List<City> selectProvince() {
        return provincesMapper.selectProvince();
    }

    @Override
    public List<City> selectCityById(int fId) {
        return provincesMapper.selectCity(fId);
    }

    @Override
    public List<City> selectRegionById(int fId) {
        return provincesMapper.selectRegion(fId);
    }

    @Override
    public List<City> selectAllCity() {
        List<City> provinces = provincesMapper.selectAllCity();
        getChildPerms(provinces, 0);
        return getChildPerms(provinces, 0);
    }


    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param fId 传入的父节点ID
     * @return String
     */

    public List<City> getChildPerms(List<City> list, int fId)
    {
        List<City> returnList = new ArrayList<City>();
        for (Iterator<City> iterator = list.iterator(); iterator.hasNext();)
        {
            City c = (City) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (c.getfId() == fId)
            {
                recursionFn(list, c);
                returnList.add(c);
            }
        }
        return returnList;
    }

    /**
     * 得到子节点列表
     */
    private List<City> getChildList(List<City> list, City t)
    {
        List<City> tlist = new ArrayList<City>();
        Iterator<City> it = list.iterator();
        while (it.hasNext())
        {
            City n = (City) it.next();
            if (n.getfId() == t.getcId())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<City> list, City t)
    {
        // 得到子节点列表
        List<City> childList = getChildList(list, t);
        t.setChildren(childList);
        for (City tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<City> list, City t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
